package mr.ali.videoapp.portal.pay;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class WxPayService {

   @Value("${wxpay.appId}")
   private String appID;

   @Value("${wxpay.mchId}")
   private String mchID;

   @Value("${wxpay.key}")
   private String key;

   @Resource
   private HttpServletRequest requests;

   public UnifiedOrderResponse unifiedOrder(UnifiedOrderRequest request) throws Exception {
      WxPayConfig config = new WxPayConfig(appID, mchID, key);
      log.info("appID:{}, mchID:{}, key:{}", appID, mchID, key);
      log.info("config:{}", config);
      WXPay wxpay = new WXPay(config);
      String userIp = requests.getRemoteAddr();
      request.setSpbillCreateIp(userIp);
      Map<String, String> data = new HashMap<>();
      data.put("body", request.getBody());
      data.put("out_trade_no", request.getOutTradeNo());
      data.put("total_fee", String.valueOf(request.getTotalFee()));
      data.put("spbill_create_ip", request.getSpbillCreateIp());
      data.put("notify_url", "https://app.erkantv.cn:443/pay/notify");
      data.put("trade_type", "JSAPI");
      data.put("openid", request.getOpenid());

      Map<String, String> response = wxpay.unifiedOrder(data);

      UnifiedOrderResponse orderResponse = new UnifiedOrderResponse();
      orderResponse.setPrepayId(response.get("prepay_id"));
      orderResponse.setNonceStr(WXPayUtil.generateNonceStr());
      orderResponse.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
      orderResponse.setPaySign(generatePaySign(orderResponse));
      log.info("response:{}", response);
      log.info("orderResponse:{}", orderResponse);
      return orderResponse;
   }

   private String generatePaySign(UnifiedOrderResponse response) throws Exception {
      Map<String, String> signMap = new HashMap<>();
      signMap.put("appId", appID);
      signMap.put("timeStamp", response.getTimeStamp());
      signMap.put("nonceStr", response.getNonceStr());
      signMap.put("package", "prepay_id=" + response.getPrepayId());
      signMap.put("signType", String.valueOf(WXPayConstants.SignType.MD5));

      return WXPayUtil.generateSignature(signMap, key);
   }
}